<template>
  <div :id="mapId" class="uni-map">
  </div>
</template>

<script>
  import * as HMAP from '../../../../components/jfMap/hmap.manage.js'
  let mapParam = {}
  let spriteControl = {}
  let colorMap = {}

  export default {
    name: 'LoraMap',
    props: {
      scaleMap: {
      	type: Object,
      	default () {
      		return {
      			'': 1 // 比例尺为 1：1000（米） 地图距离：实际距离
      		}
      	}
      },
      param: {
      	type: Object,
      	default () {
      		return {}
      	}
      }
    },
    data() {
      return {
        mapId: 'maplora_' + Math.random().toString(36).substr(2),
        mapManager: null
      }
    },
    activated() {
      if (this.mapManager) {
        this.mapManager.setMapWork(true)
      }
    },
    deactivated() {
      if (this.mapManager) {
        this.mapManager.setMapWork(false)
      }
    },
    beforeDestroy () {
      if (this.mapManager) {
        this.mapManager.destroy()
        this.mapManager = null
      }
    },
    mounted() {
      this.mapManager = new HMAP.Hmap(this.mapId, {
      	mapStorage: true, 						      // 使用地图缓存功能，加快加载速度
      	viewMode: HMAP.ViewMode.Mode_3D, 	// 初始二维还是三维状态,默认是3D状态
      });
      this.mapManager.on('onCompass', (e) => {
      	this.$emit("onCompass", e)
      })
      this.mapManager.on('onMapClick', (e) => {
        this.$emit("mapClick", e)
      })
    },
    methods: {
      // _initMap() {
      //   this.mapManager = new JFMAP.JfMap('', this.mapId, mapParam)
      //   this.mapManager.utilitieShowCondition();
      //   this.mapManager.utilitieAnimationCondition({
      //     placeIdList: ["11"]
      //   });
      //   colorMap = this._getMeshColorMap();
      //   this.mapManager.on('onCompass', (e) => {
      //   	this.$emit("onCompass", e.detail)
      //   })
      //   this.mapManager.on('mapClick', (e) => {
      //     if(e.detail.position) {
      //       console.log(e.detail.position.x+","+e.detail.position.y)
      //     }
      //     this.$emit("mapClick", e.detail)
      //   })
      // },
      getMapManager() {
        return this.mapManager
      },
      coordMapToScreen(point) {
        var floor =  this._getFloorById(point.floorId);
        if(floor) {
          return this.mapManager.coordMapToScreen(point.x, point.y, floor.floorSort*mapParam.floorHeight) //三维坐标x,y,z 转成屏幕坐标x,y
        }
        return null;
      },
      showFloors(floors) {
        // 同时展示多个楼层
        if (!this.mapManager) {
          return
        }
        for(var i=0; i<floors.length; i++) {
          var floorId = floors[i]
          var floorData = this._getFloorData(floorId);
          this.mapManager.showFloor(floorData, (state)=>{
            if(!state) {
              this._addRoomList(floorId);
              // this._addMerchants(floorId);
              this._addUtilities(floorId);
              this._addParkSpaces(floorId);
              this._drawArea(floorId);
            }
            this.mapManager.showBuilding(floors, [])
          })
        }
        this.mapManager.showBuilding(floors, [])

        var center = this._getMapCenter(floors)
        var cameraPos = this.mapManager.calCameraPosition({
        	rotateAngle: mapParam.defaultRotateAngle,
        	tiltAngle: floors.length===1 ? mapParam.defaultTiltAngle:25, //倾斜角度（摄像头与中心点连线与XY面夹角）,最大90，最小90-defaultMaxTiltAngle
        	target: center, //中心点
        	distance: mapParam.singleCameraDis //摄像头到中心点距离
        })
        if (cameraPos) {
        	this.mapManager.setCameraAndCenterPosition(cameraPos, center, 0.5)
        }
        this.resize()
      },
      showUsers(users){
        if (!this.mapManager) {
          return
        }
        users.forEach((user)=>{
          user.poiImage = this.backParam['userType'+user.userType] || "https://xcfiles.oss-cn-shanghai.aliyuncs.com/xufuji/78a9_35583aeeba030a9cf7f65b98cb5cc65e.png"
          // this.findNearPointInLu(user);
        })
        this.mapManager.showUsers(users, {
          size: 32,
          offsetZ: 0,
          depthTest: false, // 设置为false后，不被任何物体遮挡
          animation: false //是否一直保持动画
        })
      },
      // map.showUsers(user, _param)
      resize() {
        this.$nextTick(() => {
          if (this.mapManager) {
            this.mapManager._resize()
          }
        })
      },
      _getMapCenter(floors) {
      	var center = {
      		x: mapParam.defaultViewCenter.x,
      		y: mapParam.defaultViewCenter.y,
      		z: mapParam.defaultViewCenter.z
      	}

      	var minSort = 1000
      	var maxSort = -1000
      	floors.forEach((floorId) => {
      		var floor = this._getFloorById(floorId)
      		if (floor) {
      			if (floor.floorSort > maxSort) {
      				maxSort = floor.floorSort
      			}
      			if (floor.floorSort < minSort) {
      				minSort = floor.floorSort
      			}
      		}
      	})

      	center.z = mapParam.defaultViewCenter.z + (maxSort + minSort) * mapParam.floorHeight * 0.5
      	return center
      },
      showFloor(floorId, callback){
        if (!this.mapManager) {
          return
        }
        var center = this._getMapCenter([floorId])
        var cameraPos = this.mapManager.calCameraPosition({
        	rotateAngle: mapParam.defaultRotateAngle,
        	tiltAngle: mapParam.defaultTiltAngle, //倾斜角度（摄像头与中心点连线与XY面夹角）,最大90，最小90-defaultMaxTiltAngle
        	target: center, //中心点
        	distance: mapParam.singleCameraDis //摄像头到中心点距离
        })

        var floorData = this._getFloorData(floorId);
        this.mapManager.showFloor(floorData, (state)=>{
          if(!state) {
            this._addRoomList(floorId);
            // this._addMerchants(floorId);
            this._addUtilities(floorId);
            this._addParkSpaces(floorId);
            this._drawArea(floorId);
            // mapManager.networkVisible("jflu", true)
          }
          if (cameraPos) {
          	this.mapManager.setCameraAndCenterPosition(cameraPos, center, 1)
          }
          callback && callback(state)
        })
        this.mapManager.showBuilding([floorId], [])

        // if (cameraPos) {
        // 	this.mapManager.setCameraAndCenterPosition(cameraPos, center, 1)
        // }
      },
      _getFloorData(floorId) {
        // for(var i=0; i<this.floors.length; i++) {
        //   if(this.floors[i].id === floorId) {
        //     if(this.floors[i].hasOwnProperty("floorHeight")) {
        //       delete this.floors[i].floorHeight
        //     }
        //     this.floors[i]['floorId'] = this.floors[i].id
        //     this.floors[i]['colorMap'] = colorMap[this.floors[i].id] || {}
        //     return this.floors[i]
        //   }
        // }
				var floorData = {}
				for(var i=0; i<this.floors.length; i++) {
				  if(this.floors[i].id === floorId) {
				    for(var key in this.floors[i]) {
							if(key !== 'floorHeight') {
								floorData[key] = this.floors[i][key]
							}
				    }
				    floorData.floorId = floorId
				    floorData.colorMap = colorMap[this.floors[i].id] || {}
				    return floorData
				  }
				}
      },
      setViewMode(mode, callback) {
        if(this.mapManager) {
          this.mapManager.setViewMode(mode === "2D" ? JFMAP.ViewMode.Mode_25D : JFMAP.ViewMode.Mode_3D, {
            duration: 0.5
          }, callback)
        }
      },
      /**
       * 绘制小尾巴，轨迹线
       * @param {Object} points
       */
      drawTrack(points) {
        this.mapManager.drawTrackInfloor(points, {})
      },
      /**
       * 计算启动到终点直接的过度点， 必须是同一楼层
       * @param {Object} start
       * @param {Object} end
       */
      getTrackPoints(start, end) {
        if(!start || start.floorId !== end.floorId) {
          var p = this.findNearPointInLu(end)
          if(p) {
            return [p]
          } else {
            return [end]
          }
        }
        // 距离2米内，不动
        if(this._distance(start, this.findNearPointInLu(end)) < 2) {
          return [this.findNearPointInLu(start)]
        }

        var param = {
        	start: start,
        	end: end
        }
        var road = this.mapManager.findPath(param)
        if(!road) {
          return [this.findNearPointInLu(end)]
        }
        var points = this.mapManager.separateRoad(road, 1)
        if(points.length === 0) {
          return [this.findNearPointInLu(end)]
        }
        return points
      },
      findNearPointInLu(point){
        if(!point.floorId || point.floorId === '') {
          return null
        }
        return this.mapManager.findNearPointInLu({
        	point: point,
        	roadName: "jflu"
        })
      },
      _distance(point1, point2) {
      	return Math.sqrt((point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y -
      		point2.y));
      },
      _getTextImg(text, callback) {
      	var canvas = document.createElement('canvas');
      	var context = canvas.getContext('2d');
      	canvas.width = 256;
      	canvas.height = 256;
        var poi = './static/img/poi.png'
      	var imgBg = new Image();
      	imgBg.src = poi;
      	imgBg.setAttribute('crossOrigin', 'anonymous');
      	imgBg.onload = function() {
      		context.drawImage(imgBg, 0, 0, 256, 256);
          context.font = "100px 'Microsoft Yahei'";
          // 设置颜色
          context.fillStyle = "#ffffff";
          // 设置水平对齐方式
          context.textAlign = "center";
          // 设置垂直对齐方式
          context.textBaseline = "middle";
          // 绘制文字（参数：要写的字，x坐标，y坐标）
          context.fillText(text, canvas.width / 2, canvas.height / 2-25);
          context.fillText(text, canvas.width / 2, canvas.height / 2-25);

      		var baseStr = canvas.toDataURL("image/png");
      		callback && callback(baseStr)
      	};
      	imgBg.onerror =function () {
      		callback && callback(poi)
      	}
      },
      setBuildingCount(buildingId, floorId, x, y, z, count) {
        var sprite = this.mapManager.getPoiById(buildingId);
        if(sprite) {
          if(sprite.count !== count) {
            // 更新
            this.mapManager.removePoiById(buildingId)
            this._addBuildingText(buildingId,floorId, x, y, z, count)
          }
        } else {
          // 新增
          this._addBuildingText(buildingId,floorId, x, y, z, count)
        }
      },
      _addBuildingText(buildingId,floorId, x, y,z, count){
        this._getTextImg(count+"", (poiImage)=>{
          var point = {
            floorId: floorId,
            x: x,
            y: y
          }
          var sprite = this.mapManager.addPoi(point, {
          	poiImage: poiImage,
          	size: 35,
          	offsetZ: z, //z偏移
          	objId: buildingId,
          	dataType: 'building',
          	// depthTest: false, // 设置为false后，不被任何物体遮挡
          	animation:  false, //是否一直保持动画
          	autoCenter: false,
          	center: {
          		x: 0.5,
          		y: 0
          	}
          })
          if(sprite) {
            sprite.count = count
          }
        })
      },
      _drawArea(floorId) {
        for(var i=0; i<this.gsAreaList.length; i++) {
          var area = this.gsAreaList[i]
          if(area.dataType === "区域" && area.areaType === "自定义区域" && area.areaFloorId === floorId) {
            // console.log(area)
            this.mapManager.drawArea(area.areaPoints, {
              floorId: floorId,
              offsetZ: 0.05,
              depthTest: true // 设置为false后，不被任何物体遮挡
            })
          }
        }
      },
      _addRoomList(floorId) {
        this.roomList.forEach((room) => {
          if(room.floorId === floorId) {
            var _param = {
              offsetZ: room.z + 5.2, //z偏移
              dataType: 'merchant',
              merchantId: room.id, //商户id
              merchantName: room.name, //商户名称
              floorId: room.floorId, //这个公共设施所在的楼层
              x: room.x, //x坐标
              y: room.y, //y坐标
              // meshName: merchant.meshName, //对应地图中模型的名称	依情况而定
              imageUrl: "", //展示在商户名称前面的小图标，一般为业态的logo,不传则不展示	可不传
              size: 20, //字体的大小，这个大小为参考值，实际大小会以这个size上下变化	可不传
              color: "#333333", //字体的颜色		可不传
              shadowColor: "#ffffff", //字体阴影颜色	可不传
              textShowType: JFMAP.TextShowType.Sprite, //默认添加字的方式
              textType: JFMAP.TextType.CANVAS,
              // depthTest: false, // 设置为false后，不被任何物体遮挡
              userData: room //其他需要保存的数据
            }
            this.mapManager.addMerchant(_param)
          }
        })
      },
      _addMerchants(floorId) {
        this.merchants.forEach((merchant) => {
          if(merchant.floorId === floorId) {
            var _param = {
              offsetZ: merchant.z + 0.5, //z偏移
              dataType: 'merchant',
              merchantId: merchant.id, //商户id
              merchantName: merchant.name, //商户名称
              floorId: merchant.floorId, //这个公共设施所在的楼层
              x: merchant.x, //x坐标
              y: merchant.y, //y坐标
              // meshName: merchant.meshName, //对应地图中模型的名称	依情况而定
              imageUrl: "", //展示在商户名称前面的小图标，一般为业态的logo,不传则不展示	可不传
              size: 20, //字体的大小，这个大小为参考值，实际大小会以这个size上下变化	可不传
              color: "#333333", //字体的颜色		可不传
              shadowColor: "#ffffff", //字体阴影颜色	可不传
              textShowType: JFMAP.TextShowType.Sprite, //默认添加字的方式
              textType: JFMAP.TextType.CANVAS,
              // depthTest: false, // 设置为false后，不被任何物体遮挡
              userData: merchant //其他需要保存的数据
            }
            this.mapManager.addMerchant(_param)
          }
        })
      },
      _addParkSpaces(floorId) {
        this.parkSpaceList.forEach((space) => {
          if(space.floorId === floorId) {
            var name = space.spaceStart
            if (space.spaceEnd && space.spaceEnd !== '') {
              name += '~' + space.spaceEnd
            }
            space.name = name
            var param = {
              dataType: 'park',
              merchantId: space.id, //停车位id
              merchantName: name, //商户名称
              floorId: space.floorId, //这个公共设施所在的楼层
              x: space.x, //x坐标
              y: space.y, //y坐标
              meshName: space.meshName, //对应地图中模型的名称	依情况而定
              imageUrl: "", //展示在商户名称前面的小图标，一般为业态的logo,不传则不展示	可不传
              size: 12, //字体的大小，这个大小为参考值，实际大小会以这个size上下变化	可不传
              color: "#333333", //字体的颜色		可不传
              shadowColor: "#ffffff", //字体阴影颜色	可不传
              textShowType: JFMAP.TextShowType.Sprite, //默认添加字的方式
              textType: JFMAP.TextType.CANVAS,
              offsetZ: 0.2,
              // depthTest: false, // 设置为false后，不被任何物体遮挡
              // nameUrl: this.getFileUrl(merchant.nameFile),
              userData: space //其他需要保存的数据
            }
            this.mapManager.addMerchant(param)
          }
        })
      },
      _addUtilities(floorId) {
        this.utilities.forEach((utilitie) => {
          if(floorId === utilitie.floorId) {
            //11、添加公共设施,需要在楼层加载结束loadComplete事件后调用
            this.mapManager.addUtilitie({
              offsetZ: 1.5,
              dataType: 'utilitie',
              placeId: utilitie.id, //公共设施位置的id
              utilitieId: utilitie.utilitiesId, //公共设施的id
              utilitieTypeId: utilitie.utilitiesTypeId, //这个公共设施类型的id
              floorId: utilitie.floorId, //这个公共设施所在的楼层
              imageUrl: utilitie.map_logo, //图片对应的url
              size: 20, //图片展示的大小
              x: utilitie.x, //x坐标
              y: utilitie.y, //y坐标
              meshName: "", //对应地图中模型的名称
              animation: false, //是否一直保持动画
              autoCenter: false,
              // depthTest: false, // 设置为false后，不被任何物体遮挡
              center: {
                x: 0.5,
                y: 0
              },
              userData: utilitie //其他需要保存的数据
            })
          }
        })
      },
      _getMeshColorMap() {
        var colorMap = {}
        for (var i = 0; i < this.merchants.length; i++) {
          var merchant = this.merchants[i]
          if (merchant.mapColor && merchant.mapColor.length > 1 && merchant.meshName && merchant.meshName
            .indexOf("di") === -1) {
            if (!colorMap.hasOwnProperty(merchant.floorId)) {
              colorMap[merchant.floorId] = {}
            }
            colorMap[merchant.floorId][merchant.meshName] = merchant.mapColor
          }
        }
        for (var i = 0; i < this.parkSpaceList.length; i++) {
          var space = this.parkSpaceList[i]
          if (space.color && space.color.length > 1 && space.meshName && space.meshName.indexOf("di") === -1) {
            if (!colorMap.hasOwnProperty(space.floorId)) {
              colorMap[space.floorId] = {}
            }
            colorMap[space.floorId][space.meshName] = space.color
          }
        }
        return colorMap;
      },
      _getFloorById(floorId) {
        for (var i = 0; i < this.floors.length; i++) {
          if (this.floors[i].id === floorId) {
            return this.floors[i]
          }
        }
        return null
      },
    },
    computed: {
      alwaysShowUtilitiesType: {
        get() {
          return this.utilitiestype.filter((type) => {
            if (type.species === '4' || type.species === 4) {
              return true
            }
            return false
          }).map(item => {
            return item.id
          })
        }
      },
      floors: {
        get () {
          return this.$store.state.shopdata.floors
        }
      },
      merchants: {
      	get () {
      	  return this.$store.state.shopdata.merchants
      	}
      },
      roomList: {
        get () {
          return this.$store.state.shopdata.roomList
        }
      },
      elevators: {
      	get () {
      	  return this.$store.state.shopdata.elevators
      	}
      },
      utilities: {
      	get () {
      	  return this.$store.state.shopdata.utilities
      	}
      },
      utilitiestype: {
      	get () {
      	  return this.$store.state.shopdata.utilitiestype
      	}
      },
      parkSpaceList: {
      	get () {
      	  return this.$store.state.shopdata.parkSpaceList
      	}
      },
      backParam: {
        get () {
          return this.$store.state.config.backParam
        }
      },
      gsAreaList: {
        get () {
          return this.$store.state.shopdata.gsAreaList
        }
      }
    }
  }
</script>
<style scoped>
  .uni-map {
    width: 100%;
    height: 100%;
  }
</style>
